﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace WpfWordsLearner
{
	/// <summary>
	/// Interaktionslogik für "App.xaml"
	/// </summary>
	public partial class App : Application
	{
		internal static log4net.ILog Log = null;
		internal static string pathToDB;
		internal static string pathToContent;

		public App()
		{
			Log = log4net.LogManager.GetLogger(typeof(App).FullName);
			log4net.Config.XmlConfigurator.Configure();
			this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
			this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);

			string execPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

			pathToDB = System.IO.Path.Combine(execPath, @"Data\Voices.s3db");

			pathToContent = System.IO.Path.Combine(execPath, @"Content");
		}

		void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			Log.Fatal("Unhandled exception occurred", e.Exception);
			if (e.Exception is System.ServiceModel.EndpointNotFoundException)
				e.Handled = true;
			else
				e.Handled = false;
		}

		internal byte[] key = { 145, 12, 32, 245, 98, 132, 98, 214, 6, 77, 131, 44, 221, 3, 9, 50 };
		internal byte[] iv = { 15, 122, 132, 5, 93, 198, 44, 31, 9, 39, 241, 49, 250, 188, 80, 7 };

		protected override void OnStartup(StartupEventArgs e)
		{
			base.OnStartup(e);
			System.Threading.AutoResetEvent eventWait = new System.Threading.AutoResetEvent(false);


			System.Threading.Tasks.Task.Factory.StartNew(new Action(() =>
				{
					try
					{
						using (ServiceReferenceTranslater.TranslateServiceClient client = new ServiceReferenceTranslater.TranslateServiceClient())
						{
							client.Open();
							if (client.State == System.ServiceModel.CommunicationState.Opened)
								client.Close();
						}
					}
					catch (System.Exception)
					{
						System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
						System.Security.Principal.WindowsImpersonationContext ic = null;
						using (identity)
						{
							ic= identity.Impersonate();
							var serv = System.ServiceProcess.ServiceController.GetServices(Environment.MachineName).FirstOrDefault(x => x.ServiceName.Contains("SkypeMonitorService v1.0.5"));
							if (serv != null && serv.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
							{
								serv.Start();
								serv.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
							}
							ic.Undo();
							ic.Dispose();
						}
					}
					finally { eventWait.Set(); }

				}));

			string wordsDefDict = System.IO.Path.Combine(pathToContent, "Words.xml");

			WordsManager.Instance.SetPreference(wordsDefDict);

			eventWait.WaitOne(TimeSpan.FromSeconds(12));

			WpfWordsLearner.Views.Window1 window = new Views.Window1();
			ViewModels.Windows1ViewModel model = new ViewModels.Windows1ViewModel();
			window.DataContext = model;
			model.SelectedXML = wordsDefDict;

			App.Current.MainWindow = window;
			model.SetDispatcher(window.Dispatcher);
			window.Show();
		}

		protected override void OnExit(ExitEventArgs e)
		{
			base.OnExit(e);
			WordsManager.Instance.FinalSave();
			log4net.Core.LoggerManager.Shutdown();
		}
	}

}
